  <template>
  	<view class="order-page">
  		<view class="order-form-container">
  			<view class="order-form">
  				<!-- 供应商 -->
  				<view class="product-item-row">
  					<view>供应商：</view>
  					<picker mode="selector" :range="supplierNames" @change="onSupplierChange" :value="supplierIndex">
  						<view class="picker-supplier">{{ supplierNames[supplierIndex] || '请选择供应商' }}</view>
  					</picker>
  				</view>
  				<!-- 采购时间 -->
  				<view class="product-item-row">
  					<view>时间：</view>
  					<uni-datetime-picker type="date" :clear-icon="false" placeholder="请选择采购时间" v-model="orderTime" />
  				</view>
  				<!-- 产品清单 -->
  				<view class="product-list-header">
  					<view>产品清单</view>
  					<button type="primary" @click="addProduct" class="add-product-button">+添加产品</button>
  				</view>
  				<view class="product-list">
  					<view v-for="(product, index) in orderProducts" :key="index" class="product-item">
  						<view class="product-item-row">
  							<view>产品：</view>
  							<picker mode="selector" :range="productNames" @change="onProductChange(index, $event)"
  								:value="product.productIndex">
  								<view class="pickerproduct">{{ productNames[product.productIndex] || '请选择产品' }}</view>
  							</picker>
  						</view>
  						<view class="product-item-row">
  							<view>数量：</view>
  							<view class="picker">
  								<input class="uni-input" type="digit" v-model.number="product.count"
  									placeholder="请输入数量" @input="calculateAmount(index)" />
  							</view>
  						</view>
  						<view class="product-item-row">
  							<view>单价：</view>
  							<view class="picker">
  								<input class="uni-input" type="digit" v-model.number="product.productPrice"
  									placeholder="请输入单价" @input="calculateAmount(index)" />
  							</view>
  						</view>
  						<view class="product-item-row">
  							<view>税率：</view>
  							<view class="picker">
  								<input class="uni-input" type="digit" v-model.number="product.taxPercent"
  									placeholder="请输入税率" />
  							</view>
  						</view>
  						<view class="product-item-row">
  							<view>备注：</view>
  							<uni-easyinput type="textarea" autoHeight v-model="product.remark"
  								placeholder="请输入备注"></uni-easyinput>
  						</view>
  						<view class="product-item-row">
  							<button type="warn" size="mini" @click="removeProduct(index)"
  								class="delete-button">删除产品</button>
  						</view>
  					</view>
  				</view>
  				<!-- 定金金额 -->
  				<view class="product-item-row">
  					<view>定金：</view>
  					<view class="picker">
  						<input class="uni-input" type="digit" v-model.number="depositPrice" placeholder="请输入定金金额" />
  					</view>
  				</view>
  				<!-- 附件地址 -->
  				<view class="product-item-row">
  					<view>附件：</view>
  					<uni-easyinput v-model="fileUrl" placeholder="请输入附件地址" />
  				</view>
  				<!-- 备注 -->
  				<view class="product-item-row">
  					<view>备注：</view>
  					<uni-easyinput type="textarea" autoHeight v-model="remark" placeholder="请输入备注"></uni-easyinput>
  				</view>
  				<button type="primary" @click="submitOrder" class="submit-button"
  					:disabled="isSubmitting">提交订单</button>
  			</view>
  		</view>
  	</view>
  </template>

  <script>
  	import {
  		getProducts,
  		getProductCount,
  		updateSaleOrder,
  		createSaleOrder,
  		getOrderDetails
  	} from "@/sheep/api/erp/purchase.js";
  	import {
  		supplierList
  	} from "@/sheep/api/erp/supplier.js";

  	export default {
  		data() {
  			return {
  				orderId: "",
  				isEdit: false, // 是否为编辑模式
  				supplierId: null,
  				supplierIndex: -1,
  				supplierNames: [],
  				suppliers: [],
  				orderTime: "",
  				depositPrice: 0,
  				fileUrl: "",
  				remark: "",
  				orderProducts: [],
  				productNames: [],
  				products: [],
  				isSubmitting: false,
  			};
  		},
  		methods: {
  			setPageTitle() {
  				const title = this.isEdit ? "修改采购订单" : "新增采购订单";
  				uni.setNavigationBarTitle({
  					title,
  				});
  			},
  			async fetchOrderDetails() {
  				if (!this.orderId) return;
  				try {
  					const res = await getOrderDetails(this.orderId);
  					const order = res.data;
  					this.orderTime = new Date(order.orderTime).toISOString().split("T")[0];
  					this.supplierId = order.supplierId;
  					this.supplierIndex = this.suppliers.findIndex(supplier => supplier.id === order.supplierId);
  					this.depositPrice = order.depositPrice || 0;
  					this.fileUrl = order.fileUrl || "";
  					this.remark = order.remark || "";
  					this.orderProducts = order.items.map(item => {
  						const productIndex = this.products.findIndex(product => product.id === item
  							.productId);
  						return {
  							id: item.productId,
  							productIndex,
  							count: item.count,
  							productPrice: item.productPrice || 0,
  							taxPercent: item.taxPercent || 0,
  							remark: item.remark || "",
  						};
  					});
  				} catch (error) {
  					this.showToast("获取订单详情失败");
  				}
  			},
  			async fetchSuppliers() {
  				try {
  					const res = await supplierList();
  					this.suppliers = res.data;
  					this.supplierNames = this.suppliers.map(supplier => supplier.name);
  				} catch (error) {
  					this.showToast("获取供应商失败");
  				}
  			},
  			async fetchProducts() {
  				try {
  					const res = await getProducts();
  					this.products = res.data;
  					this.productNames = this.products.map(product => product.name);
  				} catch (error) {
  					this.showToast("获取产品数据失败");
  				}
  			},
  			async onProductChange(index, e) {
  				const productIndex = parseInt(e.detail.value, 10);
  				const selectedProduct = this.products[productIndex];
  				try {
  					const res = await getProductCount({
  						productId: selectedProduct.id
  					});
  					this.$set(this.orderProducts, index, {
  						...this.orderProducts[index],
  						productIndex,
  						id: selectedProduct.id,
  						count: 0,
  						productPrice: selectedProduct.salePrice,
  					});
  				} catch (error) {
  					this.showToast("获取库存失败");
  				}
  			},
  			onSupplierChange(e) {
  				this.supplierIndex = parseInt(e.detail.value, 10);
  				this.supplierId = this.suppliers[this.supplierIndex]?.id || null;
  			},
  			addProduct() {
  				this.orderProducts.push({
  					productIndex: -1,
  					id: "",
  					count: 0,
  					productPrice: 0,
  					taxPercent: 0,
  					remark: ""
  				});
  			},
  			removeProduct(index) {
  				this.orderProducts.splice(index, 1);
  			},
  			calculateAmount(index) {
  				const product = this.orderProducts[index];
  				product.amount = (product.count * product.productPrice).toFixed(2);
  			},
  			async submitOrder() {
  				if (!this.supplierId || !this.orderTime || !this.orderProducts.length) {
  					this.showToast("请填写完整订单信息");
  					return;
  				}
  				this.isSubmitting = true;
  				try {
  					const payload = {
  						id: this.orderId,
  						supplierId: this.supplierId,
  						orderTime: new Date(this.orderTime).getTime(),
  						depositPrice: this.depositPrice,
  						fileUrl: this.fileUrl,
  						remark: this.remark,
  						items: this.orderProducts.map(item => ({
  							productId: item.id,
  							count: item.count,
  							productPrice: item.productPrice,
  							taxPercent: item.taxPercent,
  							remark: item.remark,
  						})),
  					};
  					if (this.isEdit) {
  						await updateSaleOrder(payload);
  					} else {
  						await createSaleOrder(payload);
  					}
  					this.showToast("提交成功", "success");
  					uni.navigateBack();
  				} catch (error) {
  					this.showToast(`提交失败: ${error.msg}`);
  				} finally {
  					this.isSubmitting = false;
  				}
  			},
  			showToast(message, type = "none") {
  				uni.showToast({
  					title: message,
  					icon: type
  				});
  			},
  		},
  		async onLoad() {
  			this.orderId = uni.getStorageSync("orderId");
  			this.isEdit = !!this.orderId; // 如果有 productId，则为编辑模式
  			this.setPageTitle(); // 设置页面标题
  			await this.fetchSuppliers();
  			await this.fetchProducts();
  			await this.fetchOrderDetails();
  			if (!this.orderId) this.orderTime = new Date().toISOString().split("T")[0];
  		},
  	};
  </script>

  <style scoped>
  	 
  </style>